package gjj.util;

import org.opencv.core.Core;
import org.opencv.core.Mat;
import org.opencv.core.Size;
import org.opencv.imgproc.Imgproc;

import java.util.ArrayList;
import java.util.List;

public class ImageUtils {

    public static Mat getImageCopy(Mat img) {
        Mat copy = new Mat(img.rows(), img.cols(), img.type());
        img.copyTo(copy);
        return copy;
    }

    public static void adaptImgChannel(Mat img) {
        //如果不足3个通道则补成3通道的图像
        if (img.channels() < 3) {
            List<Mat> channels = new ArrayList<>(3);
            Core.split(img, channels);
            while (channels.size() < 3) {
                Mat newChannel = new Mat();
                channels.get(0).copyTo(newChannel);
                channels.add(newChannel);
            }
            Core.merge(channels, img);
        }
        //如果超过3个通道的情况下需要将4通道的图片改成3通道图片
        if (img.channels() > 3) {
            List<Mat> channels = new ArrayList<>();
            Core.split(img, channels);
            Core.merge(channels.subList(0, 3), img);
        }
    }

    public static void fitImgSize(Mat dst, int width, int height) {
        double fitRatio = (double) width / height;
        double ratio = (double) dst.width() / dst.height();
        Size imgFitSize = new Size(height * ratio, height);
        double newRatio = imgFitSize.width / imgFitSize.height;
        if (newRatio > fitRatio) {
            imgFitSize = new Size(width, width / ratio);
        }
        Imgproc.resize(dst, dst, imgFitSize);
    }
    public static void fitImgSize(Mat src, Mat dst, int width, int height) {
        double fitRatio = (double) width / height;
        double ratio = (double) src.width() / src.height();
        Size imgFitSize = new Size(height * ratio, height);
        double newRatio = imgFitSize.width / imgFitSize.height;
        if (newRatio > fitRatio) {
            imgFitSize = new Size(width, width / ratio);
        }
        Imgproc.resize(src, dst, imgFitSize);
    }
}
